package com.cqrt.aop;

import cn.hutool.core.util.ObjectUtil;
import com.cqrt.constant.RTErrorCodeEnum;
import com.cqrt.mapper.RTTaskMapper;
import com.hustcad.plm.rpm.model.dto.job.JobStatusUpdateDTO;
import com.hustcad.plm.rpm.model.dto.job.TyppmJobDTO;
import com.hustcad.plm.rpm.model.dto.remote.RemoteObjDTO;
import com.hustcad.plm.rpm.model.vo.recent.TyppmOperationRecordVO;
import com.hustcad.plm.rpm.service.job.TyppmJobService;
import com.hustcad.plm.rpm.service.remoterequest.ThirdRemoteRequestService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 项目计划完成状态切面
 * 1. 检查项目状态，确保只有在"已生效"状态下才允许查询交付物规则
 * 2. 当项目计划执行完成后，将执行状态从"正常"更新为"完成"
 * Author: zhangyu
 */
@Aspect
@Component
@Slf4j
@Order(-10)
public class ProjectPlanCompletionAop {

    @Resource
    private RTTaskMapper rtTaskMapper;
    @Resource
    private TyppmJobService typpmJobService;
    @Resource
    private ThirdRemoteRequestService thirdRemoteRequestService;
    @Around("execution(* com.hustcad.plm.rpm.service.job.TyppmJobService.setSubmitState(..))")
    public Object checkProjectStatusAndUpdatePlanStatus(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            Object[] args = joinPoint.getArgs();
            if (args != null && args.length >= 1) {
                if (args[0] instanceof JobStatusUpdateDTO) {
                    JobStatusUpdateDTO jobStatusUpdateDTO = (JobStatusUpdateDTO) args[0];
                    if (ObjectUtil.isNotNull(jobStatusUpdateDTO) && ObjectUtil.isNotNull(jobStatusUpdateDTO.getJobId())) {
                        String jobId = jobStatusUpdateDTO.getJobId();
                        log.info("开始处理任务{}的状态检查和更新", jobId);
                        // 1. 查询交付物规则与状态并进行提交校验
                        try {
                            java.util.List<TyppmJobDTO> jobs = typpmJobService.getJobByOid(jobId);
                            if (jobs == null || jobs.isEmpty()) {
                                throw RTErrorCodeEnum.RT_NON_PROJECT.getException("任务不存在，无法校验交付物规则状态");
                            }
                            TyppmJobDTO job = jobs.get(0);
                            String otype = job.getOtype();
                            String projectID = job.getProjectID();

                            java.util.List<RemoteObjDTO> deliverables = thirdRemoteRequestService.queryDeliverableByParent(jobId, otype, "OUT", projectID);
                            log.info("查询到交付物规则条目数: {}", deliverables == null ? 0 : deliverables.size());

                            if (deliverables != null && !deliverables.isEmpty()) {
                                boolean hasNotEffective = deliverables.stream()
                                        .anyMatch(item -> item.getValidStatus() == null || !"已生效".equals(item.getValidStatus()));
                                if (hasNotEffective) {
                                    throw RTErrorCodeEnum.RT_NON_EFFECTIVE.getException("存在状态非已生效的交付物，禁止提交");
                                }
                            }
                        } catch (Exception e) {
                            log.error("交付物规则状态校验失败", e);
                            throw e;
                        }
                        // 2. 执行原方法
                        Object result = joinPoint.proceed();
                        // 3. 设置任务的实际完成时间
                        try {
                            // 获取当前日期时间
                            JobStatusUpdateDTO jobStatusUpdate=new JobStatusUpdateDTO();
                            jobStatusUpdate.setJobId(jobId);
                            TyppmOperationRecordVO typpmOperationRecordVO = new TyppmOperationRecordVO();
                            typpmOperationRecordVO.setPassname("完成");
                            typpmOperationRecordVO.setRemark("");
                            jobStatusUpdate.setOperationRecordVO(typpmOperationRecordVO);
                            this.typpmJobService.setJobCompletedState(jobStatusUpdate, "已完成");
                        } catch (Exception e) {
                            log.error("设置任务{}的实际完成时间失败", jobId, e);
                        }
                        try {
                            int updateCount =0;
                            String executedStatus= rtTaskMapper.selectExecutedStatus(jobId);
                            if(StringUtils.isEmpty(executedStatus)){
                                return result;
                            }
                            if (executedStatus.equals("3")){
                                updateCount =rtTaskMapper.updateProjectPlanExecutionStatusToCompleted(jobId,"延期完成");
                            }else {
                                updateCount =rtTaskMapper.updateProjectPlanExecutionStatusToCompleted(jobId,"完成");
                            }

                            log.info("更新任务{}执行状态成功，更新行数: {}", jobId, updateCount);
                            // 查询更新后的状态
                            String afterStatus = rtTaskMapper.selectJobExecutionStatus(jobId);
                            log.info("任务{}提交后执行状态: {}", jobId, afterStatus);
                        } catch (Exception e) {
                            log.error("查询任务{}执行状态异常", jobId, e);
                        }
                        return result;
                    }
                }
            }
            return joinPoint.proceed();
        } catch (Exception e) {
            log.error("项目状态检查和更新异常", e);
            throw e; // 重新抛出异常
        }
    }
}
